/**
 * 2020年1月6日
 * 部署在外网服务器，因此不需要proxy
*/

const superagent = require("superagent");
//require("superagent-proxy")(superagent);
const charset = require("superagent-charset");
const cheerio = require('cheerio');
const userAgent = require('../tools/userAgent');
//const iconv = require('iconv-lite');
const zlib = require('zlib');

let cutText = (start, end, text) => {
    let tmp = text.substring((text.indexOf(start) + start.length));
    return tmp.substring(0, tmp.indexOf(end));
}
/**
 * 获取评论ID及相关数据
 * @param {*} skuId 
 * 京东20200220更新：不再需要获取commentVersion
 */
let getCommentVersion =  (skuId) => {
    //const proxy = "http://proxy.intra.panasonic.cn:8080";
    let _url = "https://item.jd.com/" + skuId + ".html";
    return new Promise((resolve, reject) => {
        try {
            charset(superagent)
                //superagent 
                .get(_url)
                //.proxy(proxy)
                .set("dataType", "text")
                .set({
                    Host: "item.jd.com",
                    "User-Agent":
                        "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:67.0) Gecko/20100101 Firefox/67.0",
                    Accept: "*/*",
                    "Accept-Language":
                        "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                    "Accept-Encoding": "gzip, deflate, br",
                    Referer:_url,
                    Connection: "keep-alive",
                    // Connection: "close",
                    Cookie:
                        "__jda=122270672.1573001401337726226730.1573001401.1573001401.1573023098.2; __jdc=122270672; __jdv=122270672|direct|-|none|-|1573001401338; __jdu=1573001401337726226730; areaId=2; ipLoc-djd=2-2825-51931-0; shshshfp=1e0be75baa5cbbf910664e9bd2cf9f77; shshshfpa=81da8330-e3b5-1d0d-ea86-3c1d392f0d86-1573001403; shshshfpb=pBkAbCgDcYGCeKb40TltcyA%3D%3D; 3AB9D23F7A4B3C9B=UVXMITK4IFFN5YU3HJZ7IJJ4NX3LAH6HSHN6GJ4LRQLZTQWTDSJ2OBBGYT5YYUQLLAIKZN6J3WES5U6GJL2IG5745U; __jdb=122270672.8.1573001401337726226730|2.1573023098; _gcl_au=1.1.209642543.1573023099; shshshsID=04f4701bda6df1ea6b06b5c982e80192_6_1573024966599; mt_xid=V2_52007VwMWVF9ZU1oaSBleB2EFEVVeW1VcHUgpCAdmURoBCQxOCB9PSUAAYlMQTg5aBQkDHU5bUG5WGlUNUQZZL0oYXA17AxJOXF9DWhtCGVgOYwsiUG1YYl0YQRFdAmMLGmJdXlZe",
                    Pragma: "no-cache",
                    "Cache-Control": "no-cache"
                })
                .charset()
                .buffer(true)
                .end(function (err, res) {
                    try {
                        if (err) {
                            throw err;
                        }
                        // console.log(cutText("skuid: " + skuId , "specialAttrs:", res.text));
                        if (!res || !res.text) {
                            throw new Error("获取不到 res/res.text");
                        }
                        // 京东20200220更新去除
                        // // let trim = cutText("skuid: " + skuId , "specialAttrs:", res.text);
                        // let trim = cutText("href: '//item.jd.com/" + skuId + ".html'", "specialAttrs:", res.text);
                        // // let regex = new RegExp(/(shopId\:\')[a-zA-Z0-9]*?(specialAttrs)/g);
                        // let regex = new RegExp(/(commentVersion\:\')[0-9]*?(\'\,)/g);
                        // // console.log(trim.match(regex));
                        // let comment = trim.match(regex)[0].replace("commentVersion:'", "").replace("',", "");
                        let $ = cheerio.load(res.text);
                        //2020年4月29日 发现61135891946商品获取失败，是由于页面html变动，导致CHEERIO(jquery)解析页面获取firstCategory失败，现去掉相关字段的获取                  
                        /*       
                        let href = $("ul.p-parameter-list>li").find("a")[0].attribs.href;
                        //get=>json
                        let href_params = (() => {
                            let _name, _value;
                            let _index = href.indexOf("?");
                            let _str = href.substr(_index + 1);
                            let _result = {};
                            let _arr = _str.split("&");
                            for (var i = 0; i < _arr.length; i++) {
                                _index = _arr[i].indexOf("=");
                                if (_index > 0) {
                                    _name = _arr[i].substring(0, _index);
                                    _value = _arr[i].substr(_index + 1);
                                    _result[_name] = _value;
                                }
                            }
                            return _result;
                        })(); 
                        */
                        let $chooseAttrs = $('#choose-attrs');
                        let $items = $chooseAttrs.find('.dd .item');
                        let skuCount = $items?$items.length:0;
                        let result = {
                            //callback: "fetchJSON_comment98vv" + comment,
                            callback: "fetchJSON_comment98vv",
                            // fetch_title: cutText("", "\n", $(".p-name").text().trimStart()),
                            // fetch_brand: $("ul.p-parameter-list>li")[0].attribs.title,
                            // fetch_name: $("ul.p-parameter-list>li")[1].attribs.title,
                            fetch_skuCount:skuCount,//有多个颜色号(sku)的商品的url与单个sku的商品使用不同的url获取评论，需要提前更新颜色号数
                            // firstCategory: href_params["cat"].split(',')[0],
                            // secondCategory: href_params["cat"].split(',')[1],
                            // thirdCategory: href_params["cat"].split(',')[2],
                            // exbrand: href_params["ev"],
                            //categoryCN: [].slice.call($(".crumb").find("a,.ellipsis").map(function () { return $(this).text(); })).join('>')
                        };
                        resolve(result);
                    }
                    catch (error) {
                      reject(error);
                    }
                });
        }
        catch (error) {
            reject(error);
        }
    });
}


/**
 * 获取评论详情
 //* @param {*} commentVersion 
 * @param {*} skuId 
 * @param {*} page 
 * @param {*} score 
 */

let getCommentDetail = function (summary, page, score) {
    //  console.log(new Date().toTimeString());
    let skuId = summary.skuId;
    let commentVersion = summary.callback;
    let skuCount = summary.skuCount;  
    //let url = "sclub.jd.com/comment/productPageComments.action";
      //let url = "sclub.jd.com/comment/skuProductPageComments.action";
      let url = "club.jd.com/comment/skuProductPageComments.action";//2020年3月5日
      if(skuCount<1){
        url = 'club.jd.com/comment/productPageComments.action'
      }
      let res = {};
      return new Promise((resolve, reject) => {
        try{
          charset(superagent)
          //superagent
          .get(url) //目标地址
          //.proxy(proxy1)
          //.proxy(proxy2)
          .query({
            callback: commentVersion,
            productId: skuId,
            "score": score ? score : 0,//指定类别：全部评分(0全部；4晒图；7视频晒单；5追评；321好中差)
            sortType: 6,//时间排序
            page: page,
            pageSize: 10,
            isShadowSku: 0,
            fold: 1
          })
          .set("dataType", "text")
          .set("Cookie", "JSESSIONID=760D6422C29F0E497C91BAD7135200A5.s1; Path=/")
          .set("User-Agent", userAgent.random())
          .set({
            Host: "club.jd.com",
            Accept: "*/*",
            "Accept-Language":
              "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
          /*            
          请求头不需要gzip参数，
          ※注意如果连{}等符号也是乱码，
          有可能是gzip设置问题 2020年3月9日 
            */
            //"Accept-Encoding": "gzip, deflate, br",
            Referer: "https://item.jd.com/" + skuId + ".html",
            Connection: "keep-alive",
            //Connection: "close",
            //Cookie:
            //  '__jda=122270672.1571791462338373452186.1571791462.1571791462.1571797123.2; __jdc=122270672; __jdv=76161171|direct|-|none|-|1571791462347; __jdu=1571791462338373452186; areaId=2; ipLoc-djd=2-2825-51931-0; shshshfp=1e0be75baa5cbbf910664e9bd2cf9f77; shshshfpa=5c6c897e-5184-fe49-1e5e-1677497f9503-1571791490; shshshfpb=cSZoP3lRfU2kl9OdvbUKVBw%3D%3D; JSESSIONID=F837CFAF3CFAEF79B8A312CD17863CFE.s1; 3AB9D23F7A4B3C9B=BWUY67FGFXXOWKVEYAMBPJJYW2ZDVBGQKKS2LE6J4UXD2T63RWLKM32ZTYWBU63FTX5J2NNAWXKOTFNXMJ4GCAL4WQ; shshshsID=67cf4d7840dc74f6fe84292db59b8a33_1_1571797122843; __jdb=122270672.1.1571791462338373452186|2.1571797123',
            Cookie:
            'unpl=V2_ZzNtbRJQSkAmAUIGfUlcUmICRgpLV0ASJVwVUS5LDANkAhRcclRCFnQUR1dnGVwUZwEZWUBcQRxFCEdkexhdBGYGGl9KX3MccQtOV3oYVDVXABJtQ2dDEXwIQ1V6HFwMYQYXXURSQhJyCURccilsBW8HIm0SAh9NKmZFVXsebAVmCxVbRlJHE3Q4R2R6KRdrZk4SWUtXRhR0DUZdfRxZBWEGE1pFVkEdfDhHZHg%3d; o2State={%22webp%22:true}; __jdu=15814004187441740660398; ipLoc-djd=19-1601-3633-0; user-key=01bce06a-da30-4773-9d4e-301240332215; cn=0; __jdv=122270672|direct|-|none|-|1583114651926; __jda=76161171.15814004187441740660398.1581400418.1583114652.1583718611.5; __jdb=76161171.1.15814004187441740660398|5.1583718611; __jdc=76161171; shshshfp=540024415998d3e662d04166e707e172; shshshfpa=33f8a9b5-ddde-3da0-272d-22cb0680d847-1581400448; shshshsID=a437265b5aa366ad1b111d95ae195ade_1_1583718642150; shshshfpb=mSPW1KflN4FS%20RZ%2FNqhYoVQ%3D%3D',
            Pragma: "no-cache",
            "Cache-Control": "no-cache"
          }).set('gzip',true)
          .charset()
          .buffer(true)
          .end(function (err, res) {
            if (err) {
              reject(err);
              //throw err;
            }
            //去除多余部分
            let jsonStr = res.text.substring(
              res.text.indexOf("(") + 1,
              res.text.length - 2
            );
            //console.log(JSON.parse(jsonStr));
    
            //str=>json
            //console.log(jsonStr);
            try {
              let json = JSON.parse(jsonStr);//避免json格式有误
              resolve(json);
            }
            catch (error) {
              error.res = res;
              reject(error);
            }
          });
        }
        catch(error){
          reject(error);
        }
      });
    }


    module.exports.getSummary = getCommentVersion;
    module.exports.getComments = getCommentDetail;